/**
 * Created by leiweibo on 7/25/15.
 */
var app = angular.module('researchcontroller', []);

app.filter('offset', function () {
  return function (input, start) {
    start = parseInt(start, 10);
    return input.slice(start);
  };
});


app.controller('ResearchCtrl', function ($scope, ResearchService, ProvinceService, HospitalService,
                                         $compile, OfficeService, DoctorService, $routeParams, ResearchData) {

  var data = ResearchData.get();
  if (data && !$.isEmptyObject(data)) {
    $scope.id = data._id;
    $scope.province = data.doctor.province;

    HospitalService.list_by_province(data.doctor.province, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.hospitals = res.hospitals;
    });
    $scope.hospital = data.doctor.hospital;
    OfficeService.list_by_hospital(data.doctor.hospital, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.offices = res.offices;
    });
    $scope.office = data.doctor.office;
    DoctorService.list_by_office(data.doctor.office, function(res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.doctors = res.doctors;
    });
    $scope.doctor = data.doctor._id;

    $scope.title = data.title;
    $scope.type = data.type;
    $scope.result = data.result;
    $scope.magazine = data.magazine;
    $scope.m_result = data.m_result;
    $scope.url = data.url;
    var htmlTxt = $compile("<a target='_blank' href=" + data.url + ">附件</a>")($scope);
    $("#percentage").html(htmlTxt);
  }

  var hospitalId = $routeParams.param;
  if (!hospitalId) {
    var options = {
      'expiration': Math.floor(new Date().getTime() / 1000) + 86400,
      bucket: 'vistrack-attach-prd',
      'save-key': '/{filemd5}{.suffix}'
    };
    // 查看更多参数：http://docs.upyun.com/api/form_api/#表单API接口简介
    var policy = window.btoa(JSON.stringify(options));
    // 从 UPYUN 用户管理后台获取表单 API
    //  var form_api_secret = 'uWXYXiFzo9SwavwderRAIyYJCjg=';
    var form_api_secret = '5ri+TpAfi0lw+O9eaH9PBMYoSHI=';
    // 计算签名
    var signature = md5(policy + '&' + form_api_secret);
    var url_prefix = "http://" + options.bucket + ".b0.upaiyun.com";
    var uploader = new plupload.Uploader({
      runtimes: 'html5,flash,silverlight,html4',
      browse_button: 'browser_research_title', // you can pass in id...
      container: document.getElementById('container_research_title'),
      flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
      silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
      multi_selection:false,
      url: 'http://v0.api.upyun.com/' + options.bucket,

      multipart_params: {
        'Filename': '${filename}', // adding this to keep consistency across the runtimes
        'Content-Type': '',
        'policy': policy,
        'signature': signature
      },

      init: {
        PostInit: function () {
          //do nothing here.
        },

        FilesAdded: function (up, files) {
          plupload.each(files, function (file) {
            uploader.start();
          });
        },

        UploadProgress: function (up, file) {
          $('#percentage').text(file.percent + "%");
        },

        FileUploaded: function (up, file, info) {
          var response = JSON.parse(info.response);
          $scope.url = url_prefix + response.url;
        },

        Error: function (up, err) {
          $("#percentage").text("上传失败");
        }
      }
    });
    uploader.init();
  }

  $scope.provinces = ProvinceService.list(function(data) {
    $scope.provinces = data.provinces
  });

  $scope.provinceChanged = function(provinceId) {
    $scope.hospitals = HospitalService.list_by_province(provinceId, function(res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.hospitals = res.hospitals;
    });
  }

  $scope.hospitalChanged = function (hospitalId) {
    OfficeService.list_by_hospital(hospitalId, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }

      $scope.offices = res.offices;
    });
  };

  $scope.officeChanged = function(officeId) {
    DoctorService.list_by_office(officeId, function(res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }

      $scope.doctors = res.doctors;
    });
  };

  $scope.createOrUpdate = function() {
    ResearchData.set(null);
    var formData = {
      id: $scope.id,
      doctor: $scope.doctor,
      title: $scope.title,
      url: $scope.url,
      type: $scope.type,
      result: $scope.result,
      magazine: $scope.magazine,
      m_result: $scope.m_result
    }

    console.log(formData);
    if ($scope.id) {
      ResearchService.update(formData, function(res) {
        if (res.result == true) {
          window.location = "#/research_list";
        } else {
          $scope.error_msg = res.message;
        }
      }, function(data, status) {
        $scope.error_msg = '无权限进行此操作';
      });
    } else {
      ResearchService.create(formData, function(res) {
        if (res.result == true) {
          delete $scope.id;
          delete $scope.province;
          delete $scope.hospital;
          delete $scope.office;
          delete $scope.doctor;
          delete $scope.title;
          delete $scope.url;
          delete $scope.type;
          delete $scope.result;
          delete $scope.magazine;
          delete $scope.m_result;

          $('div[id^=percentage_]').text('');
          alert('添加学术服务成功信息成功！');
        } else {
          $scope.error_msg = res.message;
        }
      }, function(data, status) {
        $scope.error_msg = '无权限进行此操作';
      });
    }

  }

  $scope.add_reasearch = function() {
    window.location = '#/create_doctor_research';
  };

  $scope.callServer = function(tableState) {
    $scope.isLoading = true;

    var pagination = tableState.pagination;
    var pageSize = pagination.number || 20;
    var pageNo = Math.ceil((pagination.start + 1) / pageSize) || 1;

    console.log('the hospitalid:' + hospitalId);
    ResearchService.list(hospitalId, pageNo, pageSize, tableState, function(res) {
      $scope.displayed = res.research;
      tableState.pagination.numberOfPages = res.pageCount;
      $scope.isLoading = false;
    });
  }

  $scope.editResearch = function(pos) {
    var targetResearch = $scope.displayed[pos];
    ResearchData.set(targetResearch);
    window.location = "#/update_doctor_research";
  }

  $scope.removeResearch = function(pos) {
    bootbox.setDefaults("locale", "zh_CN");
    bootbox.confirm("确定删除该学术服务信息吗", function (result) {
      if (result == true) {
        var search = $scope.displayed[pos];
        if (search) {
          var data = {id: search._id};
          ResearchService.delete(data, function (res) {
            if (res.result == true) {
              $scope.displayed.splice(pos, 1);
            } else {
              alert('删除数据失败');
            }
          }, function (data, status) {

          });
        } else {
          alert("请刷新重试");
        }
      }
    });
  }
});
